<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>7-编程式导航</title>
    <!-- 导入 vue 文件 -->
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
  </head>
  <body>
    <div id="app">
      <router-link to="/user1/1">User1</router-link>
      <router-link to="/user2/2">User2</router-link>
      <router-view></router-view>
    </div>
    <script>
      // 1： this.$router.push,需要跳转到的地址
      const User1 = {
        props: ['id'],
        template: `
        <div>
          <h1>User1组件 ---- ID是：{{id}},</h1>
          <button @click="goUser2">跳转到User2</button>
        </div>
        `,
        methods: {
          goUser2: function () {
            this.$router.push('/user2/2');
          },
        },
      };
      // 2：this.$router.go(-1)，需要后退的层级
      const User2 = {
        props: ['id'],
        template: `
        <div>
          <h1>User2组件 ---- ID是：{{id}},</h1>
          <button @click="goBack">后退上一次</button>
        </div>
        `,
        methods: {
          goBack: function () {
            this.$router.go(-1);
          },
        },
      };

      const router = new VueRouter({
        routes: [
          {
            path: '/',
            redirect: '/user1',
          },
          {
            path: '/user1/:id',
            component: User1,
            props: true,
          },
          {
            path: '/user2/:id',
            component: User2,
            props: true,
          },
        ],
      });
      const vm = new Vue({
        el: '#app',
        data: {},
        router,
      });
    </script>
  </body>
</html>
